const classificationModel = require('../models/classificationModel')

class ClassificationController {
    static async findList (ctx) {
        let { page, size, keyword } = ctx.query
        const total = await classificationModel.countDocuments()
        const query = {}
        if (keyword) {
            query.name = new RegExp(keyword)
        }
        size = Number(size)
        if (page && size) {
            const list = await classificationModel.find(query)
                                                  .sort({ _id: -1 })
                                                  .skip((page - 1) * size)
                                                  .limit(size)
                                                  .exec()
            ctx.body = {
                code: 1,
                data: {
                    total,
                    list,
                    page,
                    size,
                },
                msg: '成功获取分类列表',
            }
        } else {
            const list = await classificationModel.find().exec()
            ctx.body = {
                code: 1,
                data: list,
                msg: '成功获取分类列表',
            }
        }


    }

    static async create (ctx) {
        const {
            title,
        } = ctx.request.body

        const category = await classificationModel.findOne({
            title,
        }).exec()
        if (category) {
            ctx.body = {
                code: 0,
                msg: '该类别已存在',
            }
            return
        }

        const newCategory = new classificationModel({
            title,
        })

        const res = await newCategory.save()
        ctx.body = {
            code: 1,
            data: res,
            msg: '添加成功',
        }
    }

    static async update (ctx) {
        const { id, title } = ctx.request.body
        const category = await classificationModel.findOne({
            _id: id,
        }).exec()
        if (!category) {
            ctx.body = {
                code: 0,
                msg: '该类别不存在',
            }
        } else {
            category.title = title
            const res = await category.save()
            ctx.body = {
                code: 1,
                data: res,
                msg: '修改成功',
            }
        }
    }

    static async remove (ctx) {
        const { id } = ctx.params
        const res = await classificationModel.deleteOne({ _id: id })
        if (!res) {
            ctx.body = {
                code: 0,
                msg: '删除失败',
            }
        } else {
            ctx.body = {
                code: 1,
                msg: '删除成功',
            }
        }
    }
}

module.exports = ClassificationController
